package com.wx.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageHelper;
import com.wx.core.process.WxApi;
import com.wx.entity.SysWxuser;
import com.wx.entity.WxPicReply;
import com.wx.entity.WxPicReplyExample;
import com.wx.entity.WxPicReplyExample.Criteria;
import com.wx.entity.WxResource;
import com.wx.entity.WxResourceExample;
import com.wx.flag.KeyWordType;
import com.wx.service.SysWxSubscribeService;
import com.wx.service.SysWxTokenService;
import com.wx.service.SysWxuserService;
import com.wx.service.WxJsapiTicketService;
import com.wx.service.WxPicReplyService;
import com.wx.service.WxResourceService;
import com.wx.util.JsonUtil;
import com.zyht.common.AbsManageBaseController;
import com.zyht.common.bean.PropertiesUtilBean.PropertiesUtils;
import com.zyht.common.util.HttpUtils;
import com.zyht.common.util.Page;
import com.zyht.website.entity.SysUser;

/**
 * @author JSprite 功能：图文回复处理Controller
 */
@Controller
@RequestMapping("admin/pic")
@RequiresPermissions("admin:pic")
public class PicMsgConfigController extends AbsManageBaseController {

	private Logger logger = LoggerFactory.getLogger(getClass());
	@Resource
	private WxPicReplyService wxPicReplyService;
	@Resource
	private SysWxTokenService sysWxTokenService;
	@Resource
	private SysWxuserService sysWxuserService;
	@Resource
	private WxResourceService wxResourceService;
	@Resource
	private WxJsapiTicketService wxJsapiTicketService;
	@Resource
	private SysWxSubscribeService sysWxSubscribeService;

	@Value("#{propertiesReader[session_user_key]}")
	private String sessionKey;
	@Value("#{propertiesReader[session_wx_key]}")
	private String session_wx_key;

	@RequestMapping("list")
	public ModelAndView list(Integer currentPage, String search, HttpServletRequest request) {

		String wxid = getWxId(request);
		WxPicReplyExample example = new WxPicReplyExample();
		Criteria crit = example.createCriteria().andWxidEqualTo(wxid);
		if (!StringUtils.isEmpty(search)) {
			crit.andPKeywordLike("%" + search + "%");
			Criteria critOr = example.createCriteria().andWxidEqualTo(wxid);
			critOr.andTitleLike("%" + search + "%");
			example.or(critOr);
		}
		int total = this.wxPicReplyService.countByExample(example);
		example.setOrderByClause("create_time desc, p_ordery desc");

		if (null == currentPage) {
			currentPage = 1;
		}
		String pageSizeStr = PropertiesUtils.getConfig("paganation_page_size");
		int pageSize = Integer.parseInt(pageSizeStr);
		Page<WxPicReply> page = new Page<WxPicReply>(total, currentPage, pageSize);
		PageHelper.startPage(page.getCurrentPage(), pageSize);
		List<WxPicReply> list = this.wxPicReplyService.selectByExample(example);
		page.setRecordList(list);

		ModelAndView view = new ModelAndView("basic/news/list");
		view.addObject("page", page);
		view.addObject("wxid", wxid);
		view.addObject("search", search);
		return view;
	}

	@RequestMapping("ajax")
	public void picList(Integer currentPage, HttpServletRequest request, HttpServletResponse response) {

		String wxid = getWxId(request);

		WxPicReplyExample example = new WxPicReplyExample();
		example.createCriteria().andWxidEqualTo(wxid);
		int total = this.wxPicReplyService.countByExample(example);
		example.setOrderByClause("create_time desc, p_ordery desc");

		if (null == currentPage) {
			currentPage = 1;
		}
		String pageSizeStr = PropertiesUtils.getConfig("paganation_page_size");
		int pageSize = Integer.parseInt(pageSizeStr);
		Page<WxPicReply> page = new Page<WxPicReply>(total, currentPage, pageSize);
		PageHelper.startPage(page.getCurrentPage(), pageSize);
		List<WxPicReply> list = this.wxPicReplyService.selectByExample(example);
		page.setRecordList(list);
		String json = JsonUtil.Object2Json(page);
		writeJson(response, json);
	}

	@RequestMapping("/del")
	public String deleteById(Long id, Model model, HttpServletRequest request) {

		if (null != id) {
			WxPicReply entity = this.wxPicReplyService.selectByPrimaryKey(id.intValue());
			this.wxPicReplyService.deleteByPrimaryKey(id.intValue());
			// 删除图片等资源
			String linkUrl = entity.getpImgHref();
			String fileRealPath = request.getSession().getServletContext().getRealPath("/");
			File image = new File(fileRealPath + linkUrl);
			if (image.exists()) {
				image.delete();
			}
			// 删除微信media_id
			WxResourceExample wxResourceExample = new WxResourceExample();
			wxResourceExample.createCriteria().andRefIdEqualTo(entity.getId())
					.andRefTypeEqualTo(KeyWordType.TYPE_PIC.getValue());
			List<WxResource> resourceList = this.wxResourceService.selectByExample(wxResourceExample);
			String wxid = getWxId(request);
			SysWxuser user = sysWxuserService.selectByWxid(wxid);
			String token = sysWxTokenService.getAccessToken(wxid, user.getAppid(), user.getAppsecretd());
			if (StringUtils.isEmpty(token)) {
				model.addAttribute("msg", "公众丢失授权绑定");
				model.addAttribute("redirect", "admin/sysuser/list");
				return "message";
			}
			for (WxResource wxResource : resourceList) {
				String mediaId = wxResource.getMediaId();
				Map<String, String> params = new HashMap<String, String>();
				params.put("media_id", mediaId);
				params.put("access_token", token);
				String delRes = HttpUtils.post(WxApi.DEL_MATERIAL, params);
				logger.info("删除永久素材【" + wxResource.getId() + ", " + mediaId + "】返回消息： " + delRes);
				wxResourceService.deleteByPrimaryKey(wxResource.getId());
			}
		}
		model.addAttribute("msg", "删除成功");
		model.addAttribute("redirect", "admin/pic/list");
		return "message";
	}

	@RequestMapping("/add")
	public ModelAndView toAdd(String wxid) {

		ModelAndView view = new ModelAndView("basic/news/add");
		view.addObject("wxid", wxid);
		view.addObject("bean", new WxPicReply());
		view.addObject("tag", "add");
		return view;
	}

	@RequestMapping("/edit")
	public String toEdit(String wxid, Integer id, Model model) {

		WxPicReply bean = null;
		model.addAttribute("tag", "edit");
		if (null == id) {
			model.addAttribute("tag", "add");
		} else {
			id = null == id ? 0 : id;
			bean = this.wxPicReplyService.selectByPrimaryKey(id);
		}
		if (null == bean) {
			bean = new WxPicReply();
		}
		model.addAttribute("wxid", wxid);
		model.addAttribute("id", id);
		model.addAttribute("bean", bean);
		return "basic/news/add";
	}

	/**
	 * 添加图文信息
	 * 
	 * @param bean
	 * @param tag
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/persis")
	public String save(@ModelAttribute("bean") WxPicReply bean, String tag, Model model, HttpServletRequest request) {
		SysUser sysUser = getSessionUser(request);
		if ("add".equals(tag)) {
			bean.setWxid(getWxId(request));
			bean.setCreateTime(new Date());
			bean.setWatchTimes(0);
			bean.setpOrdery(0);
			bean.setUid(sysUser.getId());
			this.wxPicReplyService.insert(bean);
			model.addAttribute("msg", "保存成功");
			model.addAttribute("redirect", "admin/pic/list?wxid=" + bean.getWxid());
			return "message";
		} else if ("edit".equals(tag)) {
			this.wxPicReplyService.updateById(bean);
			model.addAttribute("msg", "保存成功");
			model.addAttribute("redirect", "admin/pic/list?wxid=" + bean.getWxid());
		} else {
			model.addAttribute("msg", "非法参数");
		}
		return "message";
	}
}
